﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace GamedataLibrary
{
    /// <summary>
    /// Trida plnici funkce serveru.
    /// </summary>
    class Server
    {
        #region Fields

        TcpListener server;
        List<ServerCommunication> clients;
        Fight fight;

        #endregion // Fields

        #region Properties

        /// <summary>
        /// Getter na vsechny klienty pripojene k serveru.
        /// </summary>
        public List<ServerCommunication> Clients { get { return clients; } }

        #endregion // Properties


        public Server(IPAddress ip, int port)
        {
            this.server = new TcpListener(ip, port);
            this.clients = new List<ServerCommunication>();

            // nastartujeme TcpListener
            server.Start();
            
            // pockame, nez se pripoji oba hraci.
            while (true)
            {
                if (server.Pending())
                {
                    Socket socket = server.AcceptSocket();

                    Console.WriteLine("New client CONNECTED!");

                    //sockets.Add(socket);

                    ServerCommunication comm = new ServerCommunication(this, socket);

                    clients.Add(comm);
                }

                if (clients.Count == 2) break;
            }

            try
            {
                while (true)
                {
                    // vytvorime novou instanci boje
                    fight = new Fight(this);

                    Console.WriteLine("New fight starts.");

                    // odstartuje boj
                    fight.Start();

                    Console.WriteLine("Fight is over.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
